from datetime import datetime
import pandas as pd
import tkinter as tk
from tkinter import scrolledtext, messagebox
import requests
import re
import akshare as ak

# DeepSeek API 相关信息
API_KEY = "sk-6b9930246f2440bcb279fd485bccc9c5"  # 替换为你自己的 API 密钥
API_URL = "https://api.deepseek.com/v1/chat/completions"

# 用户系统
USERS = {"admin": "admin123", "user": "123456","1":"1"}

# 历史记录系统
class AnalysisHistory:
    def __init__(self):
        self.history = []
        
    def add_record(self, stock_name, prompt, result):
        self.history.append({
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "stock": stock_name,
            "prompt": prompt,
            "result": result
        })

class StockAnalysisApp:
    def __init__(self, root):
        self.root = root
        self.root.title("智能股市分析系统")
        self.root.geometry("400x300+500+200")
        self.history = AnalysisHistory()
        
        # 初始化界面
        self.login_frame = None
        self.main_frame = None
        self._create_login_ui()

    def _create_login_ui(self):
        """创建登录界面"""
        if self.login_frame:
            self.login_frame.destroy()
            
        self.login_frame = tk.Frame(self.root)
        
        # 界面组件
        tk.Label(self.login_frame, text="用户登录", font=("微软雅黑", 16)).pack(pady=10)
        
        tk.Label(self.login_frame, text="用户名:").pack(pady=5)
        self.username_entry = tk.Entry(self.login_frame, width=25)
        self.username_entry.pack()
        
        tk.Label(self.login_frame, text="密码:").pack(pady=5)
        self.password_entry = tk.Entry(self.login_frame, show="*", width=25)
        self.password_entry.pack()
        
        tk.Button(self.login_frame, text="登录", command=self._verify_login, width=15).pack(pady=15)
        
        self.error_label = tk.Label(self.login_frame, text="", fg="red")
        self.error_label.pack()
        
        self.login_frame.pack(expand=True)

    def _verify_login(self):
        """验证登录信息"""
        username = self.username_entry.get()
        password = self.password_entry.get()
        
        if USERS.get(username) == password:
            self.login_successful()
        else:
            self.error_label.config(text="用户名或密码错误")
            self.error_label.after(2000, lambda: self.error_label.config(text=""))

    def login_successful(self):
        """登录成功处理"""
        self.login_frame.destroy()
        self.root.geometry("900x650")
        self._create_main_ui()

    def _create_main_ui(self):
        """创建主界面"""
        self.main_frame = tk.Frame(self.root)
        
        # 输入区域
        input_frame = tk.Frame(self.main_frame)
        tk.Label(input_frame, text="股票名称：").grid(row=0, column=0, sticky="w")
        self.stock_entry = scrolledtext.ScrolledText(input_frame, width=30, height=2)
        self.stock_entry.grid(row=1, column=0, padx=5)
        
        tk.Label(input_frame, text="分析指令：").grid(row=0, column=1, sticky="w")
        self.prompt_entry = scrolledtext.ScrolledText(input_frame, width=30, height=2)
        self.prompt_entry.grid(row=1, column=1, padx=5)
        
        # 按钮区域
        btn_frame = tk.Frame(self.main_frame)
        tk.Button(btn_frame, text="开始分析", command=self.on_analyze, width=12).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="更新数据", command=self.on_update, width=12).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="历史记录", command=self.show_history, width=12).pack(side=tk.LEFT, padx=5)
        
        # 结果展示
        self.result_text = scrolledtext.ScrolledText(self.main_frame, width=100, height=25)
        
        # 布局管理
        input_frame.pack(pady=10)
        btn_frame.pack(pady=10)
        self.result_text.pack(pady=10)
        self.main_frame.pack(expand=True, fill=tk.BOTH)

    def read_excel_file(self, file_path, stock_name):
        try:
            df = pd.read_excel(file_path)
            df.columns = df.columns.str.strip()
            if '名称' in df.columns:
                filtered_df = df[df['名称'] == stock_name]
                if filtered_df.empty:
                    messagebox.showerror("错误", f"未找到名为 {stock_name} 的股票数据")
                    return None
                return filtered_df.to_string(index=False)
            else:
                messagebox.showerror("错误", "Excel 文件中未找到 '名称' 列")
                return None
        except Exception as e:
            messagebox.showerror("错误", f"读取文件时出错: {e}")
            return None

    def analyze_data(self, data, prompt):
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {API_KEY}"
        }
        payload = {
            "model": "deepseek-chat",
            "messages": [
                {
                    "role": "user",
                    "content": f"{prompt}\n{data}"
                }
            ]
        }
        try:
            response = requests.post(API_URL, headers=headers, json=payload)
            response.raise_for_status()
            result = response.json()
            return result["choices"][0]["message"]["content"]
        except Exception as e:
            messagebox.showerror("API错误", f"接口调用失败: {str(e)}")
            return None

    def on_analyze(self):
        """执行分析操作"""
        stock_name = self.stock_entry.get("1.0", tk.END).strip()
        prompt = self.prompt_entry.get("1.0", tk.END).strip()
        
        if not stock_name or not prompt:
            messagebox.showerror("输入错误", "股票名称和分析指令不能为空")
            return
        
        try:
            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, "分析中，请稍候...")
            self.root.update()
            
            file_path = "A股数据.xlsx"
            data = self.read_excel_file(file_path, stock_name)
            if data:
                analysis_result = self.analyze_data(data, prompt)
                if analysis_result:
                    # 格式化处理
                    analysis_result = re.sub(r'^#+\s*', '', analysis_result, flags=re.MULTILINE)
                    analysis_result = re.sub(r'\*\*', '', analysis_result)
                    analysis_result = re.sub(r'^-\s*', '', analysis_result, flags=re.MULTILINE)
                    
                    self.result_text.delete(1.0, tk.END)
                    self.result_text.insert(tk.END, analysis_result)
                    self.history.add_record(stock_name, prompt, analysis_result)
        except Exception as e:
            messagebox.showerror("分析错误", f"发生错误：{str(e)}")

    def on_update(self):
        """更新数据操作"""
        try:
            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, "正在更新数据...\n")
            # df = ak.stock_zh_a_spot()
            # df.to_excel("A股数据.xlsx")
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, f"更新成功 最近更新时间: {current_time}")
        except Exception as e:
            messagebox.showerror("更新错误", f"更新失败: {str(e)}")

    def show_history(self):
        """显示历史记录"""
        history_window = tk.Toplevel(self.root)
        history_window.title("分析历史记录")
        history_window.geometry("800x400")
        
        text_area = scrolledtext.ScrolledText(history_window, width=100, height=20)
        text_area.pack(padx=10, pady=10)
        
        for record in self.history.history:
            text_area.insert(tk.END, f"时间：{record['timestamp']}\n")
            text_area.insert(tk.END, f"股票：{record['stock']}\n")
            text_area.insert(tk.END, f"指令：{record['prompt']}\n")
            text_area.insert(tk.END, f"结果：{record['result']}\n")
            text_area.insert(tk.END, "-"*80 + "\n")

if __name__ == "__main__":
    root = tk.Tk()
    app = StockAnalysisApp(root)
    root.mainloop()